package cn.tedu.boyou.website.controller;

import cn.tedu.boyou.acticle.domain.Answering;
import cn.tedu.boyou.acticle.domain.StrategyTag;
import cn.tedu.boyou.acticle.service.IAnsweringService;
import cn.tedu.boyou.acticle.service.IDestinationService;
import cn.tedu.boyou.acticle.service.IStrategyTagService;
import cn.tedu.boyou.cache.prefix.AnswerKeyPrefix;
import cn.tedu.boyou.cache.service.IAnswerKeyPrefixService;
import cn.tedu.boyou.comment.domain.AnswerComment;
import cn.tedu.boyou.comment.service.IAnswerCommentService;
import cn.tedu.boyou.common.query.AnswerCommentQuery;
import cn.tedu.boyou.common.util.AjaxResult;
import cn.tedu.boyou.member.domain.UserInfo;
import cn.tedu.boyou.search.query.AnswerQueryObject;
import cn.tedu.boyou.search.service.IAnswerSearchService;
import cn.tedu.boyou.search.template.AnswerTemplate;
import cn.tedu.boyou.website.annotation.RequireLogin;
import cn.tedu.boyou.website.annotation.UserParam;
import cn.tedu.boyou.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RequestMapping("wenda")
@Controller
public class WenDaController {


    @Value("${file.path}")
    private String filePath;


    @Reference
    private IStrategyTagService tagService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IAnsweringService answeringService;

    
    
    
    
    

    @RequestMapping("")
    @RequireLogin
    public String index(Model model){
        model.addAttribute("tags",tagService.listAll());
        model.addAttribute("dests",destinationService.getDestNameByDeep(1));
        return "wenda/index";
    }

    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        String upload = UploadUtil.upload(pic, filePath);
        return upload;
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Answering queanser, String anonymity, String atags, @UserParam UserInfo userInfo){
        if(userInfo == null){
            return new AjaxResult("请先登录",AjaxResult.CODE_TYPE_UNLOGIN);
        }
        if(anonymity!=null || "on".equals(anonymity)){
            queanser.setIsanonymity(1);
        }
        atags = atags.substring(9);
        queanser.setTags(atags);
        queanser.setAuthor(userInfo);
        Long id = answeringService.insert(queanser);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.addData(id);
        return ajaxResult;
    }

    @RequestMapping("/detail")
    public String detail(Model model,Long id){
        Answering answering = answeringService.get(id);
        answering.setViewnum(answering.getViewnum()+1);
        answeringService.updateViewnum(answering);
        String tag = answering.getTags();
        List<String> list = Arrays.asList(tag.split(","));
        List<StrategyTag> tags = tagService.getByTagId(list);
        List<AnswerComment> comms = answerCommentService.getComment(id);
        for (AnswerComment comm : comms) {
            List<AnswerComment> refComment =  answerCommentService.getRefComment(comm.getId());
            if(refComment != null){
                comm.setAnswerComments(refComment);
            }
        }
        model.addAttribute("comm",comms);
        model.addAttribute("ans",answering);
        model.addAttribute("tags",tags);
        return "wenda/detail";
    }

    @Reference
    private IAnswerCommentService answerCommentService;
    @RequestMapping("/commentAdd")
    public String commentAdd(Model model,String parentId,AnswerComment answerComment,@UserParam UserInfo userInfo){
        AnswerComment answercon = null;
        if(userInfo != null){
            answerComment.setUserId(userInfo.getId());
            answerComment.setUsername(userInfo.getNickname());
            answerComment.setCity(userInfo.getCity());
            answerComment.setHeadUrl(userInfo.getHeadImgUrl());
            answerComment.setLevel(userInfo.getLevel());
        }
        if(answerComment.getAnswerId() != null){
            answeringService.update(answerComment.getAnswerId());
        }
        if(parentId != null){
            answercon = answerCommentService.save(answerComment);
            AnswerComment parent = answerCommentService.get(parentId);
            parent.setRefComment(answercon);
            answerCommentService.update(parent);

        }else{
            answercon = answerCommentService.save(answerComment);
        }
        model.addAttribute("c",answercon);
        return "wenda/detailTpl";
    }

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") AnswerCommentQuery qo){
        List<AnswerComment> answerComments = new ArrayList<>();
        
        //test
        //List<Long> answerings  = answeringService.listAll(10);
        List<Long> answerings  = answeringService.listAll(qo.getType());
        for (Long ans : answerings) {
            AnswerComment ac = answerCommentService.getOne(ans);
            if(ac != null){
                answerComments.add(ac);
            }
        }
        int currentPage = 0;
        for(int i = 1;i < qo.getCurrentPage(); i++){
            currentPage += 5;
        }
        
        
        //测试 ;临时关闭  目前拿不到数 先做个假的
        //answerComments = answerComments.subList(currentPage,qo.getPageSize());
       AnswerComment answerCommentTest = new AnswerComment();
       answerCommentTest.setAnswerTitle("第一个问题");
       answerCommentTest.setAnswerId(1L);
       answerCommentTest.setCreateTime(new Date());
       answerCommentTest.setHeadUrl("headUrl");
       answerCommentTest.setContent("多线程的10中使用场景");
       answerCommentTest.setCity("湖南");
       answerCommentTest.setUsername("黄sir");
       answerComments.add(answerCommentTest);
       
        model.addAttribute("answers",answerComments);

        return "wenda/list";
    }
    @RequestMapping("/listTpl")
    public String listTpl(Model model, @ModelAttribute("qo") AnswerCommentQuery qo){
        List<AnswerComment> answerComments = new ArrayList<>();
        List<Long> answerings  = answeringService.listAll(qo.getType());
        for (Long ans : answerings) {
            AnswerComment ac = answerCommentService.getOne(ans);
            if(ac != null){
                answerComments.add(ac);
            }
        }
        int currentPage = 0;
        int pageSize = 5;
        int size = answerComments.size();
        size -= 5;
        for(int i = 1;i < qo.getCurrentPage(); i++){
            currentPage += 5;
            if(size!= 0 &&size>=5){
                pageSize += 5;
            }else {
                pageSize += size;
            }
        }
        answerComments = answerComments.subList(currentPage,pageSize);
        model.addAttribute("answers",answerComments);
        return "wenda/listTpl";
    }

    @RequestMapping("/stateTpl")
    public String stateTpl(Model model){
        List<Answering> getlist = answeringService.getlist();
        model.addAttribute("answers",getlist);
        return "wenda/stateTpl";
    }

    @Reference
    private IAnswerSearchService answerSearchService;
    @RequestMapping("/search")
    public String search(Model model, @ModelAttribute("qo") AnswerQueryObject qo){
        Page<AnswerTemplate> answertmp = answerSearchService.searchWithHighlight(AnswerTemplate.INDEX_NAME,
                AnswerTemplate.TYPE_NAME, AnswerTemplate.class, qo, "title", "destName","summary");
        model.addAttribute("page",answertmp);
        return "wenda/searchList";
    }

    @Reference
    private IAnswerKeyPrefixService service;
    @RequestMapping("/thumbsupnum")
    @ResponseBody
    public Object thumbsupnum(Long id,@UserParam UserInfo userInfo){
        if(userInfo == null){
            return new AjaxResult("请先登录",AjaxResult.CODE_TYPE_UNLOGIN);
        }
        boolean thumbup = service.thumbup(AnswerKeyPrefix.ANSWER_KEY_THUMBSUP, id, userInfo.getId());
        AnswerComment comment = answerCommentService.getOne(id);
        int i = comment.getThumbsupnum();
        if(thumbup){
            i = comment.getThumbsupnum() + 1;
            comment.setThumbsupnum(i);
            answerCommentService.updateThumbsupnum(comment);
        }
        return new AjaxResult(thumbup,"").addData(i);
    }


}
